<?php

module_load_include('inc', 'user', 'user.admin');

function system_reform_user_admin($callback_arg = '') {
  $op = isset($_POST['op']) ? $_POST['op'] : $callback_arg;
  switch ($op) {
    case t('Create new account'):
    case 'create':
      $output = drupal_get_form('system_reform_user_register');
      break;
    default:
      if (!empty($_POST['accounts']) && isset($_POST['operation']) && ($_POST['operation'] == 'delete')) {
        $output = drupal_get_form('system_reform_user_multiple_delete_confirm');
      } else {
        $output = drupal_get_form('system_reform_filter_form', 'user', array('role' => 0, 'permission' => 1, 'status' => 0), 'user');
        $output .= drupal_get_form('system_reform_user_admin_account_form');
      }
  }
  return $output;
}

function system_reform_user_register() {
  $form = user_register();
  $form['#submit'][] = 'user_register_submit';
  return $form;
}

function system_reform_user_build_filter_query() {
  $filters = user_filters();
  $where = $args = $join = array();
  $session = array();
  foreach ($_SESSION['system_reform_user_overview_filter'] as $key => $value) {
    if ($value != '')
      $session[] = array($key, $value);
  }
  foreach ($session as $filter) {
    list($key, $value) = $filter;
    if ($key == 'permission') {
      $account = new stdClass();
      $account->uid = 'user_filter';
      $account->roles = array(DRUPAL_AUTHENTICATED_RID => 1);
      if (user_access($value, $account)) {
        continue;
      }
    }
    $where[] = $filters[$key]['where'];
    $args[] = $value;
    $join[] = $filters[$key]['join'];
  }
  $where = !empty($where) ? 'AND ' . implode(' AND ', $where) : '';
  $join = !empty($join) ? ' ' . implode(' ', array_unique($join)) : '';

  return array('where' => $where, 'join' => $join, 'args' => $args);
}

function system_reform_user_admin_account_form() {
  $filter = system_reform_user_build_filter_query();
  $header = array(
      array(),
      array('data' => t('Username'), 'field' => 'u.name'),
      array('data' => t('Status'), 'field' => 'u.status'),
      t('Roles'),
      array('data' => t('Member for'), 'field' => 'u.created', 'sort' => 'desc'),
      array('data' => t('Last access'), 'field' => 'u.access'),
      t('Operations')
  );

  if ($filter['join'] != "") {
    $sql = 'SELECT DISTINCT u.uid, u.name, u.status, u.created, u.access FROM {users} u LEFT JOIN {users_roles} ur ON u.uid = ur.uid ' . $filter['join'] . ' WHERE u.uid != 0 ' . $filter['where'];
    $query_count = 'SELECT COUNT(DISTINCT u.uid) FROM {users} u LEFT JOIN {users_roles} ur ON u.uid = ur.uid ' . $filter['join'] . ' WHERE u.uid != 0 ' . $filter['where'];
  } else {
    $sql = 'SELECT u.uid, u.name, u.status, u.created, u.access FROM {users} u WHERE u.uid != 0 ' . $filter['where'];
    $query_count = 'SELECT COUNT(u.uid) FROM {users} u WHERE u.uid != 0 ' . $filter['where'];
  }


  $sql .= tablesort_sql($header);

  $result = pager_query($sql, 50, 0, $query_count, $filter['args']);

  $form['options'] = array(
      '#type' => 'fieldset',
      '#title' => t('Update options'),
      '#prefix' => '<div class="container-inline">',
      '#suffix' => '</div>',
  );
  $options = array();
  foreach (module_invoke_all('user_operations') as $operation => $array) {
    $options[$operation] = $array['label'];
  }
  $form['options']['operation'] = array(
      '#type' => 'select',
      '#options' => $options,
      '#default_value' => 'unblock',
  );
  $form['options']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Update'),
  );

  $destination = drupal_get_destination();

  $status = array(t('blocked'), t('active'));
  $roles = user_roles(TRUE);
  $accounts = array();
  while ($account = db_fetch_object($result)) {
    $accounts[$account->uid] = '';
    $form['name'][$account->uid] = array('#value' => theme('username', $account));
    $form['status'][$account->uid] = array('#value' => $status[$account->status]);
    $users_roles = array();
    $roles_result = db_query('SELECT rid FROM {users_roles} WHERE uid = %d', $account->uid);
    while ($user_role = db_fetch_object($roles_result)) {
      $users_roles[] = $roles[$user_role->rid];
    }
    asort($users_roles);
    $form['roles'][$account->uid][0] = array('#value' => theme('item_list', $users_roles));
    $form['member_for'][$account->uid] = array('#value' => format_interval(time() - $account->created));
    $form['last_access'][$account->uid] = array('#value' => $account->access ? t('@time ago', array('@time' => format_interval(time() - $account->access))) : t('never'));
    $form['operations'][$account->uid] = array('#value' => l(t('edit'), "user/$account->uid/edit", array('query' => $destination)));
  }
  $form['accounts'] = array(
      '#type' => 'checkboxes',
      '#options' => $accounts
  );
  $form['pager'] = array('#value' => theme('pager', NULL, 50, 0));
  $form['#theme'] = 'user_admin_account';
  return $form;
}

function system_reform_user_admin_account_form_validate($form, &$form_state) {
  $form_state['values']['accounts'] = array_filter($form_state['values']['accounts']);
  if (count($form_state['values']['accounts']) == 0) {
    form_set_error('', t('No users selected.'));
  }
}

function system_reform_user_admin_account_form_submit($form, &$form_state) {
  $operations = module_invoke_all('user_operations', $form_state);
  $operation = $operations[$form_state['values']['operation']];
  // Filter out unchecked accounts.
  $accounts = array_filter($form_state['values']['accounts']);
  if ($function = $operation['callback']) {
    // Add in callback arguments if present.
    if (isset($operation['callback arguments'])) {
      $args = array_merge(array($accounts), $operation['callback arguments']);
    } else {
      $args = array($accounts);
    }
    call_user_func_array($function, $args);

    drupal_set_message(t('The update has been performed.'));
  }
}

function system_reform_user_multiple_delete_confirm(&$form_state) {
  $edit = $form_state['post'];

  $form['accounts'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
  foreach (array_filter($edit['accounts']) as $uid => $value) {
    $user = db_result(db_query('SELECT name FROM {users} WHERE uid = %d', $uid));
    $form['accounts'][$uid] = array('#type' => 'hidden', '#value' => $uid, '#prefix' => '<li>', '#suffix' => check_plain($user) . "</li>\n");
  }
  $form['operation'] = array('#type' => 'hidden', '#value' => 'delete');

  return confirm_form($form, t('Are you sure you want to delete these users?'), 'admin/systemreform/user', t('This action cannot be undone.'), t('Delete all'), t('Cancel'));
}

function system_reform_user_multiple_delete_confirm_submit($form, &$form_state) {
  if ($form_state['values']['confirm']) {
    foreach ($form_state['values']['accounts'] as $uid => $value) {
      user_delete($form_state['values'], $uid);
    }
    drupal_set_message(t('The users have been deleted.'));
  }
  $form_state['redirect'] = 'admin/system_reform/user';
  return;
}

?>